Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = "traffic-signs-data/train.p"
validation_file = "traffic-signs-data/valid.p"
testing_file = "traffic-signs-data/test.p"
sign_names_file = 'signnames.csv'


with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
with open(sign_names_file) as f:
    class_names = list(map( lambda x: x.strip().split(',')[1], f.readlines() ))
    class_names=class_names[1:] # strip header

    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']


import tensorflow as tf 
print(tf.__version__)
0.12.1

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results
import numpy as np
# TODO: Number of training examples
n_train = np.shape(train['features'])[0]

# TODO: Number of testing examples.
n_test = np.shape(test['features'])[0]

# TODO: What's the shape of an traffic sign image?
image_shape = (np.shape(train['features'])[1], np.shape(train['features'])[2])

# TODO: How many unique classes/labels there are in the dataset.
n_classes = np.size(np.unique(train['labels']))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [3]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline

n_train_by_class=[]
for label,name in enumerate(class_names):
    n = sum(np.where(y_train==label,1,0))
    n_train_by_class.append(n)
plt.rcdefaults()

fig, ax = plt.subplots(figsize=(5,10))

# Example data
y_pos = np.arange(n_classes)

ax.barh(y_pos, n_train_by_class,
        color='yellow', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(class_names)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Number of Training Examples')
ax.set_title('Number of Training Examples by Class')

plt.show()
/home/carnd/anaconda3/envs/carnd-term1/lib/python3.5/site-packages/matplotlib/font_manager.py:280: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  'Matplotlib is building the font cache using fc-list. '
In [4]:
r=len(class_names)
c=15
plt.rcdefaults()

fig,ax = plt.subplots(figsize=(10,30))
examples=[]
for idx in range(r+1):
    if idx >= len(class_names):
        break
    cls_idx = np.argwhere(y_train==idx)
    np.random.shuffle(cls_idx)
    examples.append(np.hstack(X_train[cls_idx[0:c,0]]))
ax.imshow( np.vstack(examples))
ax.set_yticks(np.arange(n_classes)*image_shape[0]+image_shape[0]/2)
ax.set_yticklabels(class_names)
ax.set_xticks([])
plt.show()
In [5]:
from random import sample
from collections import Counter

count_dict = Counter(train['labels'])
labels_count = sorted(count_dict.items(), key=lambda item:item[0])

bar_values = [item[1] for item in labels_count]
bar_labels = [item[0] for item in labels_count]
N = 5

ind = np.arange(n_classes)  # the x locations for the groups
width = 0.12       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, bar_values, width, color='b')

# add some text for labels, title and axes ticks
ax.set_ylabel('Count')
ax.set_title('Distribution of Training Set Labels')
ax.set_xticks(ind + width)
ax.set_xticklabels(bar_labels)

def autolabel(rects):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width(), 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)

plt.show()

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

Pre-process 1: Augment training set

In [6]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import random
import cv2

# Randomly rotate training set. ([-15, 15] angles)
rotated_train = {'features': [], 'labels': []}
for img, label in zip(train['features'], train['labels']):
    RotateMatrix = cv2.getRotationMatrix2D(center=(img.shape[1]/2, img.shape[0]/2), angle=random.uniform(-15, 15), scale=1)
    rotated_train['features'].append(cv2.warpAffine(img, RotateMatrix, (img.shape[0], img.shape[1])))
    rotated_train['labels'].append(label)
    

# Randomly perturbe training set in position. (on x/y axis, [-2,2] pixels)
perturbed_train = {'features': [], 'labels': []}
for img, label in zip(train['features'], train['labels']):
    pixel = random.sample([-2, -1, 1, 2], 1)[0]
    TranslationMatrix = np.array([[1, 0, pixel],
                                  [0, 1, 0]], dtype=np.float32)
    perturbed_train['features'].append(cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1])))
    perturbed_train['labels'].append(label)
    
    pixel = random.sample([-2, -1, 1, 2], 1)[0]
    TranslationMatrix = np.array([[1, 0, 0],
                                  [0, 1, pixel]], dtype=np.float32)
    perturbed_train['features'].append(cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1])))
    perturbed_train['labels'].append(label)

big_train = {
        'features':
            np.concatenate([train['features'], rotated_train['features'], perturbed_train['features']]),
        'labels':
            np.concatenate([train['labels'], rotated_train['labels'], perturbed_train['labels']])
    }

print(np.shape(big_train['features']), np.shape(big_train['labels']))

sample_idxes = sample(range(n_train), 3)

fig = plt.figure()
for i in range(3):
    ax = fig.add_subplot(2, 3, i+1)
    img = train['features'][sample_idxes[i],:,:,:]
    ax.imshow(img)
    
    RotateMatrix = cv2.getRotationMatrix2D(center=(img.shape[1]/2, img.shape[0]/2), angle=random.uniform(-15, 15), scale=1)
    rotated_img = cv2.warpAffine(img, RotateMatrix, (img.shape[0], img.shape[1]))
    ax = fig.add_subplot(2, 3, i+4)
    ax.imshow(rotated_img)

plt.show()

fig = plt.figure()
for i in range(3):
    img = train['features'][sample_idxes[i],:,:,:]
    pixel = random.sample([-2, -1, 1, 2], 1)[0]
    TranslationMatrix = np.array([[1, 0, pixel],
                                  [0, 1, 0]], dtype=np.float32)
    vertical_img = cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1]))
    ax = fig.add_subplot(2, 3, i+1)
    ax.imshow(vertical_img)
    
    pixel = random.sample([-2, -1, 1, 2], 1)[0]
    TranslationMatrix = np.array([[1, 0, 0],
                                  [0, 1, pixel]], dtype=np.float32)
    he_img = cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1]))
    ax = fig.add_subplot(2, 3, i+4)
    ax.imshow(he_img)
    
plt.show()
(139196, 32, 32, 3) (139196,)

Pre-process 2: Grayscale

In [7]:
gray_train = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in big_train['features']]
gray_valid = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in valid['features']]
gray_test = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in test['features']]

gray_train = np.reshape(gray_train, (len(gray_train), 32, 32, -1))
gray_valid = np.reshape(gray_valid, (len(gray_valid), 32, 32, -1))
gray_test = np.reshape(gray_test, (len(gray_test), 32, 32, -1))

print(np.shape(gray_train))

fig = plt.figure()
for i in range(3):
    ax = fig.add_subplot(2, 3, i+1)
    img = train['features'][sample_idxes[i],:,:,:]
    ax.imshow(img)

    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    ax = fig.add_subplot(2, 3, i+4)
    ax.imshow(img, 'gray')

plt.show()
(139196, 32, 32, 1)

Model Architecture

In [8]:
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
from sklearn.utils import shuffle
from tensorflow.contrib.layers import flatten

EPOCHS = 60
BATCH_SIZE = 100
rate = 0.001
mu = 0
sigma = 0.1
l2_lambda = 5e-4

def conv2d(x, W, b, strides=1, padding='VALID'):
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding=padding)
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k=2):
    return tf.nn.max_pool(
        x,
        ksize=[1, k, k, 1],
        strides=[1, k, k, 1],
        padding='VALID')

def lrn(inputs, depth_radius=2, alpha=0.0001, beta=0.75, bias=1.0):
    return tf.nn.local_response_normalization(inputs, depth_radius=depth_radius, alpha=alpha, beta=beta, bias=bias)
In [9]:
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, n_classes)

with tf.name_scope('Variances'):
    weights = {
        'wc1_1': tf.Variable(tf.truncated_normal([9, 9, 1, 32])),
        'wc1_2': tf.Variable(tf.truncated_normal([5, 5, 1, 32])),
        'wc2_1': tf.Variable(tf.truncated_normal([5, 5, 32, 128])),
        'wc2_2': tf.Variable(tf.truncated_normal([9, 9, 32, 128])),
        'wc3': tf.Variable(tf.truncated_normal([3, 3, 256, 512])),
        'wd1': tf.Variable(tf.truncated_normal([8192, 2048])),
        'wd2': tf.Variable(tf.truncated_normal([2048, 2048])),
        'out': tf.Variable(tf.truncated_normal([2048, n_classes]))}

    biases = {
        'bc1_1': tf.Variable(tf.truncated_normal([32])),
        'bc1_2': tf.Variable(tf.truncated_normal([32])),
        'bc2_1': tf.Variable(tf.truncated_normal([128])),
        'bc2_2': tf.Variable(tf.truncated_normal([128])),
        'bc3': tf.Variable(tf.truncated_normal([512])),
        'bd1': tf.Variable(tf.truncated_normal([2048])),
        'bd2': tf.Variable(tf.truncated_normal([2048])),
        'out': tf.Variable(tf.truncated_normal([n_classes]))}

with tf.name_scope('conv1_1'):
    conv1_1 = conv2d(x, weights['wc1_1'], biases['bc1_1'])
    conv1_1 = lrn(conv1_1)
    
with tf.name_scope('pool1_1'):
    conv1_1 = maxpool2d(conv1_1, k=2)

with tf.name_scope('conv1_2'):
    conv1_2 = conv2d(x, weights['wc1_2'], biases['bc1_2'], padding='SAME')
    conv1_2 = lrn(conv1_2)

with tf.name_scope('pool1_2'):
    conv1_2 = maxpool2d(conv1_2, k=2)

with tf.name_scope('conv2_1'):
    conv2_1 = conv2d(conv1_1, weights['wc2_1'], biases['bc2_1'])
    conv2_1 = lrn(conv2_1)
#     conv2_1 = maxpool2d(conv2_1, k=2)

with tf.name_scope('conv2_2'):
    conv2_2 = conv2d(conv1_2, weights['wc2_2'], biases['bc2_2'])
    conv2_2 = lrn(conv2_2)
#     conv2_2 = maxpool2d(conv2_2, k=2)
    
with tf.name_scope('conv3'):
    reshaped_conv = tf.concat(1, [tf.reshape(conv2_1, [-1, 8192]), tf.reshape(conv2_2, [-1, 8192])])
    reshaped_conv = tf.reshape(reshaped_conv, [-1, 8, 8, 256])
    conv3 = conv2d(reshaped_conv, weights['wc3'], biases['bc3'], padding='SAME')

with tf.name_scope('pool3'):
    conv3 = maxpool2d(conv3, k=2)

reshaped_conv3 = tf.reshape(conv3, [-1, 8192])

with tf.name_scope('fc1'):
    fc1 = tf.add(tf.matmul(reshaped_conv3, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
#     fc1 = tf.nn.dropout(fc1, keep_prob)

with tf.name_scope('fc2'):
    fc2 = tf.add(tf.matmul(fc1, weights['wd2']), biases['bd2'])
    fc2 = tf.nn.relu(fc2)
#     fc2 = tf.nn.dropout(fc2, keep_prob)
    

with tf.name_scope('output'):
    logits = tf.add(tf.matmul(fc2, weights['out']), biases['out'])
    predicts = tf.argmax(logits, 1)

with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
    loss_operation = tf.reduce_mean(cross_entropy)
    for weights, biases in zip(weights.values(), biases.values()):
        loss_operation += l2_lambda * (tf.nn.l2_loss(weights) + tf.nn.l2_loss(biases))
    summary = [tf.summary.scalar('Log_Loss', tf.log(loss_operation))]

with tf.name_scope('optimizer'):
    global_step = tf.Variable(0)
    lr = 0.001
    dr = 0.96
    learning_rate = tf.train.exponential_decay(
        learning_rate=lr,
        global_step=global_step*BATCH_SIZE,
        decay_steps=20,
        decay_rate=dr,
        staircase=True
    )
    optimizer = tf.train.AdamOptimizer(learning_rate)
    training_operation = optimizer.minimize(loss_operation)

with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(predicts, tf.argmax(one_hot_y, 1))
    accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

merged_summary = tf.summary.merge(summary)

writer = tf.summary.FileWriter('./board', tf.get_default_graph())

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the test set but low accuracy on the validation set implies overfitting.

In [10]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
In [11]:
def evaluate(X_data, y_data, kp=1.):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:kp})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
In [12]:
sess = tf.Session()

with sess.as_default():
    sess.run(tf.global_variables_initializer())
    num_examples = len(gray_train)

    print("Training...")
    print()
    k = 1
    for i in range(EPOCHS):
        X_train, y_train = shuffle(gray_train, big_train['labels'])
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            _, summary_result = sess.run([training_operation, merged_summary], feed_dict={x: batch_x, y: batch_y, keep_prob: .5})
            writer.add_summary(summary_result, k)
            k += 1
#             train_accuracy = evaluate(batch_x, batch_y)
#             validation_accuracy = evaluate(gray_valid, valid['labels'])
#             print("Train Accuracy = {:.9f}".format(train_accuracy))
#             print("Validation Accuracy = {:.9f}".format(validation_accuracy))
#             print()
    
        train_accuracy = evaluate(gray_train, big_train['labels'])
        validation_accuracy = evaluate(gray_valid, valid['labels'])

        print("EPOCH {} ...".format(i+1))
        print("Train Accuracy = {:.9f}".format(train_accuracy))
        print("Validation Accuracy = {:.9f}".format(validation_accuracy))
        print()
        
    saver = tf.train.Saver(tf.global_variables())
    saver.save(sess,"checkpoint.data")
Training...

EPOCH 1 ...
Train Accuracy = 0.798068912
Validation Accuracy = 0.786621327

EPOCH 2 ...
Train Accuracy = 0.850714105
Validation Accuracy = 0.802040818

EPOCH 3 ...
Train Accuracy = 0.917504820
Validation Accuracy = 0.830839000

EPOCH 4 ...
Train Accuracy = 0.922591176
Validation Accuracy = 0.872335606

EPOCH 5 ...
Train Accuracy = 0.949150847
Validation Accuracy = 0.877777788

EPOCH 6 ...
Train Accuracy = 0.938848824
Validation Accuracy = 0.863492068

EPOCH 7 ...
Train Accuracy = 0.947951098
Validation Accuracy = 0.883446717

EPOCH 8 ...
Train Accuracy = 0.958332145
Validation Accuracy = 0.902947859

EPOCH 9 ...
Train Accuracy = 0.970753477
Validation Accuracy = 0.912925173

EPOCH 10 ...
Train Accuracy = 0.960142540
Validation Accuracy = 0.907709755

EPOCH 11 ...
Train Accuracy = 0.963339471
Validation Accuracy = 0.901360551

EPOCH 12 ...
Train Accuracy = 0.974517952
Validation Accuracy = 0.913151934

EPOCH 13 ...
Train Accuracy = 0.979482176
Validation Accuracy = 0.906802725

EPOCH 14 ...
Train Accuracy = 0.983289754
Validation Accuracy = 0.915192752

EPOCH 15 ...
Train Accuracy = 0.984094375
Validation Accuracy = 0.930839007

EPOCH 16 ...
Train Accuracy = 0.987341595
Validation Accuracy = 0.926303855

EPOCH 17 ...
Train Accuracy = 0.977765170
Validation Accuracy = 0.908843542

EPOCH 18 ...
Train Accuracy = 0.991465276
Validation Accuracy = 0.923129256

EPOCH 19 ...
Train Accuracy = 0.984769683
Validation Accuracy = 0.915873023

EPOCH 20 ...
Train Accuracy = 0.990466685
Validation Accuracy = 0.918820867

EPOCH 21 ...
Train Accuracy = 0.992952387
Validation Accuracy = 0.934240363

EPOCH 22 ...
Train Accuracy = 0.990301450
Validation Accuracy = 0.934013611

EPOCH 23 ...
Train Accuracy = 0.993649246
Validation Accuracy = 0.926077107

EPOCH 24 ...
Train Accuracy = 0.992499788
Validation Accuracy = 0.955102050

EPOCH 25 ...
Train Accuracy = 0.993713903
Validation Accuracy = 0.944444451

EPOCH 26 ...
Train Accuracy = 0.991443723
Validation Accuracy = 0.941496604

EPOCH 27 ...
Train Accuracy = 0.994202422
Validation Accuracy = 0.937868489

EPOCH 28 ...
Train Accuracy = 0.995660797
Validation Accuracy = 0.952380961

EPOCH 29 ...
Train Accuracy = 0.992140583
Validation Accuracy = 0.934467128

EPOCH 30 ...
Train Accuracy = 0.996221158
Validation Accuracy = 0.932879819

EPOCH 31 ...
Train Accuracy = 0.997327511
Validation Accuracy = 0.953968261

EPOCH 32 ...
Train Accuracy = 0.996034370
Validation Accuracy = 0.953741503

EPOCH 33 ...
Train Accuracy = 0.995703902
Validation Accuracy = 0.934240366

EPOCH 34 ...
Train Accuracy = 0.996645020
Validation Accuracy = 0.945351481

EPOCH 35 ...
Train Accuracy = 0.996680941
Validation Accuracy = 0.949659869

EPOCH 36 ...
Train Accuracy = 0.996249894
Validation Accuracy = 0.940136059

EPOCH 37 ...
Train Accuracy = 0.996372024
Validation Accuracy = 0.951927438

EPOCH 38 ...
Train Accuracy = 0.995524299
Validation Accuracy = 0.952154200

EPOCH 39 ...
Train Accuracy = 0.995761375
Validation Accuracy = 0.951020412

EPOCH 40 ...
Train Accuracy = 0.996213974
Validation Accuracy = 0.941496603

EPOCH 41 ...
Train Accuracy = 0.996695309
Validation Accuracy = 0.951700687

EPOCH 42 ...
Train Accuracy = 0.997485562
Validation Accuracy = 0.945804994

EPOCH 43 ...
Train Accuracy = 0.997801662
Validation Accuracy = 0.950793653

EPOCH 44 ...
Train Accuracy = 0.997765742
Validation Accuracy = 0.952380962

EPOCH 45 ...
Train Accuracy = 0.996486970
Validation Accuracy = 0.968253974

EPOCH 46 ...
Train Accuracy = 0.996515706
Validation Accuracy = 0.962131530

EPOCH 47 ...
Train Accuracy = 0.997923792
Validation Accuracy = 0.957823133

EPOCH 48 ...
Train Accuracy = 0.997643612
Validation Accuracy = 0.963718831

EPOCH 49 ...
Train Accuracy = 0.997284406
Validation Accuracy = 0.958049897

EPOCH 50 ...
Train Accuracy = 0.997291590
Validation Accuracy = 0.958049893

EPOCH 51 ...
Train Accuracy = 0.998347655
Validation Accuracy = 0.948526081

EPOCH 52 ...
Train Accuracy = 0.998699676
Validation Accuracy = 0.960770981

EPOCH 53 ...
Train Accuracy = 0.997679532
Validation Accuracy = 0.964625856

EPOCH 54 ...
Train Accuracy = 0.997183829
Validation Accuracy = 0.952607714

EPOCH 55 ...
Train Accuracy = 0.998132131
Validation Accuracy = 0.956689344

EPOCH 56 ...
Train Accuracy = 0.998642203
Validation Accuracy = 0.950793656

EPOCH 57 ...
Train Accuracy = 0.997780110
Validation Accuracy = 0.952607717

EPOCH 58 ...
Train Accuracy = 0.998124947
Validation Accuracy = 0.956916112

EPOCH 59 ...
Train Accuracy = 0.998807438
Validation Accuracy = 0.966439916

EPOCH 60 ...
Train Accuracy = 0.998124947
Validation Accuracy = 0.955328803

In [31]:
with sess.as_default():
    test_accuracy = evaluate(gray_test, test['labels'])
    print("Test Accuracy = {:.9f}".format(test_accuracy))
Test Accuracy = 0.947268437

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [32]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os

test_images = os.listdir('./testimgs')
testdata = [cv2.resize(cv2.imread('./testimgs/' + image),(32,32),interpolation=cv2.INTER_AREA) for image in test_images]

fig = plt.figure()
for i in range(len(testdata)):
    ax = fig.add_subplot(2, 3, i+1)
    ax.imshow(testdata[i])
plt.show()

For first image, the label is **

Predict the Sign Type for Each Image

In [33]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
gray_testdata = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in testdata]
gray_testdata = np.reshape(gray_testdata, (len(gray_testdata), 32, 32, -1))

with sess.as_default():
    softmax_probabilities, results = sess.run([tf.nn.softmax(logits), predicts], feed_dict={x: gray_testdata, keep_prob: 1.})

print(results)
[ 1 12 38 30 34]

Analyze Performance

According to the signames.csv file, the prediction result are as follows:

  • The first image is predicted as "Speed limit (30km/h)" sign. Correct
  • The second image is predicted as "Priority road" sign. Correct
  • The third image is predicted as " Keep right" sign. Correct
  • The fourth image is predicted as "Beware of ice/snow" sign. Correct
  • The fifth image is predicted as "Turn left ahead" sign. Correct

So, the model predicted all of these signs correctly, it's 100% accurate on these new images.

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [34]:
with sess.as_default():
    top_5_logits = sess.run(tf.nn.top_k(logits, k=5), feed_dict={x: gray_testdata, keep_prob: 1.})
    
print(top_5_logits)
TopKV2(values=array([[ 3002407.75  ,  2098761.5   ,  1314941.375 ,  1243740.25  ,
         1042306.4375],
       [ 8117783.5   ,  3902181.    ,  1216163.125 ,   982649.875 ,
          904448.125 ],
       [ 7370561.5   ,  3215804.25  ,  2330247.75  ,  1707326.125 ,
         1492557.125 ],
       [ 7491763.5   ,  6958841.5   ,  1936115.75  ,  1898225.125 ,
         1484000.75  ],
       [ 7310720.    ,  4443056.    ,  3791546.25  ,  1745910.375 ,
         1732462.625 ]], dtype=float32), indices=array([[ 1,  2, 38, 31,  0],
       [12, 40,  7, 32,  1],
       [38, 34, 36, 40, 25],
       [30, 11, 19, 23, 34],
       [34, 38, 36, 35, 25]], dtype=int32))
In [35]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
with sess.as_default():
    top_probablities = sess.run(tf.nn.top_k(softmax_probabilities))
In [36]:
import pandas as pd
    
def get_label_map(filename, questnums):
    label_df = pd.read_csv(filename)
    label_map = []
    for questnum in questnums:
        label_map.extend(label_df[label_df['ClassId']==questnum].SignName.get_values())
    return label_map

top_labels = [get_label_map('signnames.csv', index) for index in top_probablities.indices]
In [37]:
top_labels
Out[37]:
[['Speed limit (30km/h)'],
 ['Priority road'],
 ['Keep right'],
 ['Beware of ice/snow'],
 ['Turn left ahead']]
In [38]:
for  i, (labels, probs, candidate) in enumerate(zip(top_probablities.indices,top_probablities.values, testdata)):
    fig = plt.figure(figsize=(15,2))
    plt.bar(labels, probs)
    plt.title(top_labels[i][0])
    height = candidate.shape[0]
    plt.xticks(np.arange(.5, 43.5, 1.), get_label_map('signnames.csv', np.unique(y_train)), ha='right', rotation=45)
    plt.yticks(np.arange(0., 1., .1), np.arange(0., 1., .1))

    ax = plt.axes([.75, .25, .5, .5], frameon=True)
    ax.imshow(candidate)
    ax.axis('off')
    
plt.show()

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the IPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.